import 'dart:io';

import 'package:cookie_jar/cookie_jar.dart';
import 'package:dio/adapter.dart';
import 'package:dio/dio.dart';
import 'package:dio_cookie_manager/dio_cookie_manager.dart';
import 'package:dio_http_cache/dio_http_cache.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_archer/env.dart';
import 'http_config.dart';

class AppDio with DioMixin implements Dio {
  AppDio({BaseOptions? options, HttpConfig? dioConfig}) {
    options ??= BaseOptions(
      baseUrl: dioConfig?.baseUrl ?? "",
      contentType: 'application/json;charset=utf-8',
      connectTimeout: dioConfig?.connectTimeout,
      sendTimeout: dioConfig?.sendTimeout,
      receiveTimeout: dioConfig?.receiveTimeout,
    )..headers = dioConfig?.headers;
    this.options = options;

    // DioCacheManager
    interceptors.add(DioCacheManager(CacheConfig(baseUrl: Env.envConfig.httpConfig.baseUrl)).interceptor);
    // Cookie管理
    if (dioConfig?.cookiesPath?.isNotEmpty ?? false) {
      interceptors.add(CookieManager(
          PersistCookieJar(storage: FileStorage(dioConfig!.cookiesPath))));
    }

    if (kDebugMode) {
      interceptors.add(LogInterceptor(
          responseBody: true,
          error: true,
          requestHeader: true,
          responseHeader: true,
          request: false,
          requestBody: true));
    }
    if (dioConfig?.interceptors?.isNotEmpty ?? false) {
      interceptors.addAll(dioConfig!.interceptors!);
    }
    httpClientAdapter = DefaultHttpClientAdapter();
    setupClientAdapter(dioConfig);
  }

  setupClientAdapter(HttpConfig? dioConfig) {
    (httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = (client) {
      // config the proxy
      if (dioConfig?.proxy?.isNotEmpty ?? false) {
        client.findProxy = (uri) {
          // proxy all request to localhost:8888
          return "PROXY "+ dioConfig!.proxy!;
        };
      }

      // config the https
      if (dioConfig?.pem?.isNotEmpty ?? false) {
        client.badCertificateCallback=(X509Certificate cert, String host, int port){
          if(cert.pem==dioConfig!.pem){ // Verify the certificate
            return true;
          }
          return false;
        };
      }
    };
  }
}
